<template>
  <div>
    <fieldset>
      <legend>收货人信息</legend>
      <el-form :model="recipent" ref="recipent" :rules="rules" label-position="right" label-width="10em">
        <el-form-item label="收货人地址" prop="addr" required>
          <el-input v-model="recipent.addr"></el-input>
        </el-form-item>
        <el-form-item label="收货人姓名" prop="name" required>
          <el-input v-model="recipent.name"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="tel" required>
          <el-input v-model="recipent.tel"></el-input>
        </el-form-item>
      </el-form>
    </fieldset>
    <fieldset>
      <legend>商品清单</legend>
      <el-table :data="cartlst">

        <el-table-column label="书名" prop="name"></el-table-column>
        <el-table-column label="作者" prop="author"></el-table-column>
        <el-table-column label="出版社" prop="house"></el-table-column>

        <el-table-column label="售价" prop="sellPrice">
          <template slot-scope="scope">
            {{ scope.row.sellPrice | price }}
          </template>
        </el-table-column>

        <el-table-column label="数量" prop="cnt"></el-table-column>

      </el-table>
    </fieldset>
    <fieldset>
      <h3>总价：{{ sum | price }}</h3>
      <el-button class="submitbtn" @click="submit" type="primary" round>确认订单</el-button>
    </fieldset>
  </div>
</template>

<script>
import { int2price } from '@/utils/format'
import ShoppingCart from '@/utils/ShoppingCart'
import { CustomPostOrder } from '@/utils/request'

export default {
  data () {
    return {
      recipent: {
        addr: '上海市闵行区东川路500号上海交通大学后花园',
        name: '有个人',
        tel: '12345678902'
      },
      rules: {
        addr: { required: true, message: '请输入收货人地址', trigger: 'blur' },
        name: { required: true, message: '请输入收货人姓名', trigger: 'blur' },
        tel: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { type: 'string', message: '请输入正确的手机号码', pattern: /^1[\d]{10}$/ }
        ]
      },
      cartlst: []
    }
  },
  filters: {
    price (value) {
      return int2price(value, true)
    }
  },
  computed: {
    sum () {
      let sum = 0
      for (let item of this.cartlst) {
        sum += item.cnt * item.sellPrice
      }
      return sum
    }
  },
  methods: {
    submit () {
      CustomPostOrder(this.recipent).then(rsp => {
        this.$notify({
          title: '成功提交订单'
        })
        ShoppingCart.clear()
        this.$router.push({
          name: 'CustomOrder'
        })
      })
    }
  },
  created () {
    this.cartlst = Object.assign([], ShoppingCart.loadFromCookie())
  }
}
</script>

<style lang="scss" scoped>
.el-form-item {
  margin: 0;
}
.submitbtn {
  float: right;
}
</style>
